//###############
//FILE : FileReceiveSession.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############

package oop.ex3.protocol.sessions;

import oop.ex3.protocol.messages.WantFileMsg;
import oop.ex3.protocol.messages.FileMsg;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import oop.ex3.exceptions.InvalidMessageException;

/**
 * This session is in charge of asking another FM for a file and receiving it.
 * @author daniel
 */
public class FileReceiveSession extends FileToFileSession {
    private DataOutputStream _fileOutput;
    private String _fileName;

    /**
     * Create a new session.
     */
    public FileReceiveSession() {
        super (new WantFileMsg());
    }

    /**
     * Set the name of the file we want to ask for.
     * @param fileName The file we want.
     */
    public void setFileName(String fileName) {
        _fileName = fileName;
    }

    /**
     * Set the output stream that we want to write to.
     * @param fileOutput The output stream.
     */
    public void setFileOutput(DataOutputStream fileOutput) {
        _fileOutput = fileOutput;
    }

    @Override
    protected boolean specExecuteSession(DataInputStream inputStream, DataOutputStream outputStream) throws IOException, InvalidMessageException {
        //first ask for the file
        WantFileMsg wantFile = new WantFileMsg();
        wantFile.setFileName(_fileName);
        wantFile.send(outputStream);
        
        //receive the file
        FileMsg fileMsg = new FileMsg();
        fileMsg.setFileOutputStream(_fileOutput);
        fileMsg.receive(inputStream);

        return true;
    }
    
}
